<template>
  <el-drawer
    size="1200px"
    title="发送短信"
    direction="rtl"
    :model-value="true"
    :before-close="handleCancel"
  >
    <div class="form-wrapper">
      <el-form
        class="custom-form"
        ref="form"
        :rules="rules"
        :model="form"
        label-width="80px"
        :disabled="readOnly"
      >
      <el-form-item label="组件名称" prop="name">
          <el-input class="custom-input custom-input-name"
            v-model.trim="form.name"
            type="text"
            maxlength="15"
            :show-word-limit="true">
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="手机号" prop="phones">
          <el-autocomplete
            class="custom-input custom-input-name"
            v-model="form.phones"
            value-key="propertyName"
            :fetch-suggestions="querySearch"
            placeholder="请输入手机号"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item> -->

        <el-form-item label="选择模板" prop="content">
          <el-select
            v-model="form.smsId"
            placeholder="请选择"
            @change="smsIdsChange()"
          >
            <el-option
              v-for="item in smsModuleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- <div v-if="form.keysList.length">
          <el-form-item
            v-for="(item, idx) in form.keysList"
            :key="idx"
            :label="item.name"
            prop="content"
          >
            <el-autocomplete
              class="custom-input custom-input-name"
              v-model="item.key"
              value-key="name"
              @click.left="index = idx"
              :fetch-suggestions="codeQuerySearch"
              placeholder="请输入属性值"
              @select="setExpression"
            ></el-autocomplete>
          </el-form-item>
        </div> -->

        <el-form-item>
          <set-variable-pub
            v-if="isDefault"
            :isCareat="isCareat"
            :domData="domData"
            @subRuleForm="subRuleForm"
          ></set-variable-pub>
        </el-form-item>
        <el-form-item label="模板内容">
          <el-input
            class="custom-input custom-input-name"
            v-model="form.initialContent"
            type="textarea"
            readonly
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div class="form-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>
    <WechatPreviewMessage
      class="wechat-prevaiew"
      :content="form.content"
    ></WechatPreviewMessage>
  </el-drawer>
</template>

<script>
import CanvasApi from "@/api/canvasApi";
import setVariablePub from "@/components/marketingCanvas/component/setVariablePub.vue";
import {NodeDrawerDataModel} from "@/views/workTable/dataModel/NodeDrawerDataModel";
export default {
  props: {
    dialogData: Object,
    addNodeEventData: Object,
    readOnly: Boolean,
  },
  components: {
    setVariablePub,
  },
  data() {
    return {
      isDefault: false,
      isCareat: true,
      content: '',
      domData: {
        content: "",
        data: {},
      },
      index: 0,
      propertyList: [],
      smsModuleList: [],

      valueList: [], // 变量值
      form: {
        phones: "{{$_user.$_phone}}",
        content: "",
        initialContent: "",
        smsId: "",
        keysList: [], // 变量key
        data: {}, // 用来回显的数据
        name: '发送短信',
      },
      reachType: 1,
      rules: {
        name: [
          {
            required: true,
            message: "请输入组件名称",
            trigger: ["blur", "change"],
          },
        ],
        phones: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  async created() {
    this.getValueList();
    await this.getSmsTemplate();
    this.getPropertyList();
    if (this.dialogData && Object.keys(this.dialogData).length) {
      if(this.dialogData.reachBody) {
        this.form = JSON.parse(this.dialogData.reachBody);
      }
      this.form.name = this.dialogData.name || '发送短信'
      this.isCareat = false
      this.smsIdsChange();
    }
  },
  methods: {
    subRuleForm(form) {
      // ruleForm.data = form
      // 
      this.form.data = form
      let initialContent = this.form.initialContent;
      for (let item in form) {
        if(form[item].value) {
          let key = new RegExp(`{{${item}.DATA}}`, "g")
          initialContent = initialContent.replace(key,form[item].value);

        }
        // 
      }
     
      this.form.content = initialContent;
      

    },

    getValueList() {
      this.valueList = [
        ...this.$store.state.event.eventObj.property,
        // ...this.$store.state.event.eventObj.event,
        // ...this.$store.state.event.publicEvent,
      ];
      
    },

    // 设置表达式
    setExpression(item) {
      
      // 先等待index赋值
      this.$nextTick(() => {
        this.form.keysList[this.index].key = `{{$_user.${item.propertyKey}}}`;
      });
    },
    getConfigId () {
      let configId = ""
      this.smsModuleList.find(item=> {
        if(item.id === this.form.smsId) {
          configId = item.configId
        }
      })
      return configId
    },
    smsIdsChange() {
      const regex = /\{{(.+?)\}}/g; // {{}} 匹配双花括号
      let variableList = []
      this.smsModuleList.forEach((item) => {
        if (item.id == this.form.smsId) {
          
          this.form.initialContent = item.content;
          this.form.content = item.content;
          this.domData.content = item.content;
          this.domData.data = this.form.data // 回显数据
          variableList = item.content.match(regex) || [];
        }
      });
      if(variableList.length) {
        this.isDefault = true;
      } else {
        this.isDefault = false;
      }
    },

    // 获取短信模板
    async getSmsTemplate() {
      let params = {
        currentPage: 1,
        showCount: -1,
        name: "",
      };
      let rs = await CanvasApi.getSmsTemplate(params);
      if (rs.code === 200) {
        this.smsModuleList = rs.payload;
      }
    },

    handleSelect(item) {
      this.form.phones = `{{$_user.${item.propertyKey}}}`;
    },

    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.propertyName.indexOf(queryString) === 0;
      };
    },


    querySearch(queryString, cb) {
      let restaurants = this.valueList;
      let results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      cb(results);
    },


    getPropertyList() {
      this.propertyList = JSON.parse(
        JSON.stringify(this.$store.state.event.eventObj.property)
      );
    },
    handleCancel() {
      this.$emit("cancel");
    },

    handleConfirm() {
    
      this.$emit("confirm", new NodeDrawerDataModel({
        dialogData: {
          name: this.form.name,
          configId: this.getConfigId(),
          reachBody: JSON.stringify(this.form),
          reachType: this.reachType,
        },
      }));
      
      this.handleCancel();
    },
  },
};
</script>

<style scoped lang="scss">
.form-wrapper {
  padding: 20px;
}

.custom-input-name {
  width: 440px;
}

.custom-input-anchor-input {
  width: 104px;
}

.form-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.custom-form {
  flex: 1;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.public-form-dialog .el-form-item) {
  margin-bottom: 10px;
}
.wechat-prevaiew {
  position: fixed;
  top: 10%;
  right: 30px;
}
</style>
